package com.terrynoya.fight.combat
{
	import com.terrynoya.fight.char.Entity;

	public class EntityCollection extends EngineObject 
	{
		private var _entities:Array;
		
		private var _removeList:Array;
		
		public function EntityCollection(engine:FightEngine)
		{
			this._removeList = new Array();
			this._entities = new Array();
			super(engine);
		}
		
		public function add(value:Entity):void
		{
			value.engine = this.engine;
			this._entities.push(value);
			if(value is Helper)
			{
				var helper:Helper = Helper(value);
				helper.getBasePlayer().addHelper(helper);
			}
		}
		
		public function getChildAt(index:int):Entity
		{
			return this._entities[index];
		}
		
		public function get length():int 
		{
			return this._entities.length;
		}
		
		public function update(time:int):void
		{
			this.runEntityUpdates(this._entities);
			this.removeCheck();
			this.removeEntities();
		}
		
		private function runEntityUpdates(entities:Array):void
		{
			this.cleanUp(entities);
			this.updateInput(entities);
			this.updateAnimation(entities);
			this.updateState(entities);
			this.updatePhysics(entities);
		}
		
		private function removeCheck():void
		{
			for (var i:int = this._entities.length - 1; i > 0 ; i--) 
			{
				var entity:Entity = this._entities[i];
				if(entity.removeCheck())
				{
					this.remove(entity);
					this._removeList.push(entity);
				}
			}
		}
		
		private function removeEntities():void
		{
			for (var i:int = 0; i < this._removeList.length; i++) 
			{
				var entity:Entity = this._removeList[i];
				entity.remove();
			}
			this._removeList = [];
		}
		
		private function remove(entity:Entity):void
		{
			var index:int = this._entities.indexOf(entity);
			this._entities.splice(index,1);
		}
		
		private function updateInput(entities:Array):void
		{
			for (var i:int = 0; i < entities.length; i++) 
			{
				var entity:Entity = entities[i];
				entity.updateInput();
			}
		}
		
		private function cleanUp(entities:Array):void
		{
			for (var i:int = 0; i < entities.length; i++) 
			{
				var entity:Entity = entities[i];
				entity.cleanUp();
			}
		}
		
		private function updateAnimation(entities:Array):void
		{
			for (var i:int = 0; i < entities.length; i++) 
			{
				var entity:Entity = entities[i];
				entity.updateAnimations();
			}
		}
		
		private function updatePhysics(entities:Array):void
		{
			for (var i:int = 0; i < entities.length; i++) 
			{
				var entity:Entity = entities[i];
				entity.updatePhysics();
			}
		}
		
		private function updateState(entities:Array):void
		{
			for (var i:int = 0; i < entities.length; i++) 
			{
				var entity:Entity = entities[i];
				entity.updateState();
			}
		}
	}
}